<?php

/**
 * 数据操作模型基类
 *
 * 主要实现常用操作方法，复杂操作由各个子类自行实现
 *
 */
class BaseModel
{
    /** @var \Vendor\Kmodel  */
    public $db;

    public $tableName;

    public function __construct($tableName)
    {
        $this->db = new \Vendor\Kmodel($tableName);
    }

    public function find($cond, $field = '*')
    {
        if (empty($cond)) return [];
        return $this->db->field($field)->where($cond)->find();
    }

    public function findAll($cond = [], $field = '*', $orderBy = '', $offset = 0, $limit = 1000)
    {
        return $this->db->field($field)->where($cond)->order($orderBy)->limit($offset, $limit)->select();
    }

    public function update($cond, $data)
    {
        if (empty($data) || empty($cond)) return false;
        return $this->db->where($cond)->set($data);
    }

    public function delete($cond)
    {
        if (empty($cond)) return false;
        return $this->db->where($cond)->delete();
    }

    public function insert($data)
    {
        if (empty($data)) return false;
        return $this->db->add($data);
    }

    public function max($field)
    {
        if (empty($field)) return false;
        return $this->db->max($field);
    }

    public function min($field)
    {
        if (empty($field)) return false;
        return $this->db->min($field);
    }

    public function count($cond = array())
    {
        return $this->db->where($cond)->count();
    }

    public function sum($field)
    {
        if (empty($field)) return false;
        return $this->db->sum($field);
    }

    public function action($actions)
    {
        if (is_callable($actions)) {
            \Vendor\DB::startTrans();

            $result = $actions($this);

            if ($result === false) {
                \Vendor\DB::rollback();
                return false;
            } else {
                \Vendor\DB::commit();
            }

        }
        return true;
    }

    public function setInc($cond,$field,$setup = 1) {
        if(empty($cond) || empty($field)) return false;
        return $this->db->where($cond)->setInc($field,$setup);
    }

    public function setDec($cond,$field,$setup = 1) {
        if(empty($cond) || empty($field)) return false;
        return $this->db->where($cond)->setDec($field,$setup);
    }
}
